-----------------------------------------------------------------------------------------
--
-- game.lua
-- Background graphic from http://opengameart.org/content/starfield-background, courtesy of Sauer2
-- buggi, enemy, and bullet graphics are from http://www.vickiwenderlich.com/2013/05/free-game-art-space-buggi/
--
-----------------------------------------------------------------------------------------

-- Require in some of Corona's 
local movieclip = require('movieclip')
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()

-- include Corona's "physics" library
local physics = require "physics"
physics.start(); physics.pause()

local numberOfLives = 3
local bulletSpeed = 0.35
local virusMovementSpeed = 1500
local virusCreationSpeed = 800

-- forward declarations and other locals
local background, tmr_createVirus, buggi, bullet, txt_score
local tmr_addCreateVirus
local lives = {}
local virus = {}
local virusCounter = 1
local score = 0
local shot = audio.loadSound("sounds/shot.mp3")
local shoted = audio.loadSound("sounds/shoted.mp3")
local bgsound = audio.loadSound( "sounds/jungle.mp3" )
local damage = audio.loadSound( "sounds/damage.mp3" )
local hit

-- Called when the scene's view does not exist:
function scene:createScene( event )
	local group = self.view	
	audio.pause(bgsound)
	audio.play(bgsound, -1)

	-- Create a background for our game
	background = display.newImageRect("images/background_3.png", 480, 320)
		background.x = halfW
		background.y = halfH
		group:insert(background)


	local circle = display.newImageRect("images/circle.png",100,100)
		circle.x = halfW
		circle.y = halfH
		group:insert(circle)
	-- rotation cicle
	local function updateCLock(e)  
    	circle.rotation = - system.getTimer()/25;      
	end 
	timer.performWithDelay(1, updateCLock, 1000)

	buggi = movieclip.newAnim({'images/ladybug_1.png', 'images/ladybug_1.png', 'images/ladybug_2.png', 'images/ladybug_2.png', 'images/ladybug_3.png', 'images/ladybug_3.png', 'images/ladybug_4.png', 'images/ladybug_4.png', 'images/ladybug_5.png', 'images/ladybug_5.png', 'images/ladybug_6.png', 'images/ladybug_6.png'})
		buggi.x = halfW
		buggi.y = halfH
		group:insert(buggi)
	buggi:play()

	txt_score = display.newText(score,20,20,font,25)
		txt_score.x = 450
		group:insert(txt_score)

		-- Insert our lives
	for i=1,numberOfLives do
		lives[i] = display.newImageRect("images/heart.png",45,34)
			lives[i].x = i*40-20
			lives[i].y = 18
			group:insert(lives[i])
	end

	local virusScore = display.newImage("images/virus2_2.png" )
	virusScore.width = 40
	virusScore.height = 40
	virusScore.x = 410
	virusScore.y = 20
	group:insert(virusScore)
	function touched(event)		

		if(event.phase == "began") then
			audio.play(shot)

			angle = math.deg(math.atan2((event.y-buggi.y),(event.x-buggi.x)))            
            buggi.rotation = angle + 90

            -- add bullet when touched
			bullet = movieclip.newAnim({'images/monster_1.png','images/monster_2.png','images/monster_3.png','images/monster_4.png','images/monster_5.png','images/monster_6.png'})
				bullet.x = halfW
				bullet.y = halfH				
				bullet.name = "bullet"
				physics.addBody( bullet, "dynamic", { isSensor=true, radius=screenH*.025} )
				group:insert(bullet)
			bullet:play()

			local farX = screenW*2
			-- the 
			local slope = ((event.y-screenH/2)/(event.x-screenW/2))			
			local b = event.y - (slope*event.x)

			if(event.x >= screenW/2)then
				farX = screenW*2
			else
				farX = screenW-(screenW*2)
			end

			local farY = (slope*farX)+b
			
			local xfactor = farX-bullet.x
			local yfactor = farY-bullet.y
			
			local distance = math.sqrt((xfactor*xfactor) + (yfactor*yfactor))
			print( bullet.x )
			print( bullet.y )

			bullet.trans = transition.to(bullet, { time=distance/bulletSpeed, y=farY, x=farX, onComplete=nil})
		end
	end

	-- This function will create our bad guy
	function createVirus(path)		
		return function()
			-- Determine the enemies starting position
			local startingPosition = math.random(1,4)
			display.remove( hit )
			if(startingPosition == 1) then
				-- Send bad guy from left side of the screen
				startingX = -10
				startingY = math.random(0,screenH)
			elseif(startingPosition == 2) then
				-- Send bad guy from right side of the screen
				startingX = screenW + 10
				startingY = math.random(0,screenH)
			elseif(startingPosition == 3) then
				-- Send bad guy from the top of the screen
				startingX = math.random(0,screenW)
				startingY = -10
			else
				-- Send bad guy from the bototm of the screen
				startingX = math.random(0,screenW)
				startingY = screenH + 10
			end

			-- Start the bad guy according to starting position
			virus[virusCounter] = display.newImageRect(path,34,34)
				virus[virusCounter].x = startingX
				virus[virusCounter].y = startingY
				physics.addBody( virus[virusCounter], "dynamic", { isSensor=true, radius=17} )
				virus[virusCounter].name = "virus"
				group:insert(virus[virusCounter])
			-- Then move the bad guy towards the center of the screen. Once the transition is done, remove the bad guy.
			
			virus[virusCounter].trans = transition.to(virus[virusCounter], { time=virusMovementSpeed, x=halfW, y=halfH, 			
			onComplete = function (self)
				if (numberOfLives > 0) then 
					audio.play(damage)
				end
				-- hit = display.newImageRect("images/ladybug_hit.png",50,50)
				-- hit.x = halfW
				-- hit.y = halfH
				-- group:insert(hit)

				
				hit = movieclip.newAnim({'images/ladybug_hit_1.png','images/ladybug_hit_2.png','images/ladybug_hit_3.png','images/ladybug_hit_4.png','images/ladybug_hit_5.png'})
					hit.x = halfW
					hit.y = halfH				
					hit.name = "hit"
					physics.addBody( hit, "static", { isSensor=true, radius=screenH*.025} )
					group:insert(hit)
				hit:play()

				self.parent:remove(self); 
				self = nil;

				-- Since the bad guy has reached the buggi, we will want to remove a heart
				display.remove(lives[numberOfLives])
				numberOfLives = numberOfLives - 1			

				-- If the numbers of lives reaches 0 or less, it's game over!
				if(numberOfLives <= 0) then
					display.remove(buggi)
					timer.cancel(tmr_createVirus)
					background:removeEventListener("touch", touched)

					
					if ( img_gameover == nil ) then
						img_gameover = display.newImage("images/GameOver.png")
						img_gameover.width = 400
						img_gameover.height = 100
						img_gameover.x = halfW
						img_gameover.y = screenH * 0.3
						group:insert(img_gameover)
					end
					local function onGameOverTouch(event)
						if(event.phase == "began") then
							storyboard.gotoScene("menu")
						end
					end
					
					local btn_return = display.newImage("images/ReturnButton.png" )
						btn_return.width = 70
						btn_return.height = 70
						btn_return.x = halfW
						btn_return.y = screenH * 0.8
						btn_return:removeEventListener("touch",onGameOverTouch)
						btn_return:addEventListener("touch",onGameOverTouch)
						group:insert(btn_return)

					display.remove( hit )
				end
			end; })

			virusCounter = virusCounter + 1
		end
	end

	-- This function handles the collisions. In our game, this will remove the bullet and bad guys when they collide. 
	function onCollision( event )		
		if(event.object1.name == "virus" and event.object2.name == "bullet" or event.object1.name == "bullet" and event.object2.name == "virus") then			
			audio.play(shoted)
			-- Update the score
			score = score + 1
			print(score)
			txt_score.text = score
			if (score % 10 == 0) then
				timer.performWithDelay(0, createVirus("images/virus2_2.png"),1)
				timer.performWithDelay(0, createVirus("images/virus2_2.png"),1)
			end

			virusMovementSpeed = virusMovementSpeed - 15
			

			-- Make the objects invisible
			--event.object1.alpha = 0
			--event.object2.alpha = 5	

			
			
			-- Cancel the transitions on the object
			transition.cancel(event.object1.trans)
			transition.cancel(event.object2.trans)			

			-- Then remove the object after 1 cycle. Never remove display objects in the middle of collision detection. 
			local function removeObjects()	
				if (event.object1.name=="bullet") then			
					display.remove(event.object1)
				end
				if (event.object2.name=="bullet") then
					display.remove(event.object2)
				end
			end
			timer.performWithDelay(1, removeObjects, 1)
		end
	end
end

function scene:enterScene( event )
	local group = self.view

	-- Actually start the game!	
	physics.start()	
	tmr_createVirus = timer.performWithDelay(virusCreationSpeed, createVirus("images/virus2_2.png"),-1)
	background:addEventListener("touch", touched)
	Runtime:addEventListener( "collision", onCollision )
end
function scene:exitScene( event ) 
	Runtime:removeEventListener( "collision", onCollision )
	-- score:removeSelf( )
	img_gameover = nil
end
function scene:destroyScene( event ) 

end

scene:addEventListener( "createScene", scene )
scene:addEventListener( "enterScene", scene )
scene:addEventListener("exitScene", scene)
scene:addEventListener("destroyScene", scene)

return scene